package com.ddm.service.impl.vxImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddm.constant.MessageConstant;
import com.ddm.constant.VXConstant;
import com.ddm.context.BaseContext;
import com.ddm.dto.vxDTO.QuestionDTO;
import com.ddm.entity.vxEntity.Question;
import com.ddm.entity.vxEntity.WrongQuestion;
import com.ddm.enumeration.QuestionType;
import com.ddm.exception.DataErrorException;
import com.ddm.mapper.QuetsionsMapper;
import com.ddm.mapper.UserMapper;
import com.ddm.mapper.WrongQuestionMapper;
import com.ddm.service.vxService.WrongQuestionService;
import com.ddm.vo.vxVo.WrongQuestionScoreVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.AccessType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WrongQuestionServiceImpl extends ServiceImpl<WrongQuestionMapper, WrongQuestion> implements WrongQuestionService {

    @Autowired
    WrongQuestionMapper wrongQuestionMapper;
    @Autowired
    QuetsionsMapper quetsionsMapper;
    @Autowired
    UserMapper userMapper;
    @Override
    @Transactional
    public WrongQuestionScoreVO wrongQuestionRedo(List<QuestionDTO> questionDTOS) {
        int CorrectQuestionNum = 0;
        int WrongQuestionNum = 0;
        int totalScores = 0;
        for (QuestionDTO questionDTO : questionDTOS) {
            if (questionDTO==null){
                throw new DataErrorException(MessageConstant.NULL_DATA);
            }
            LambdaQueryWrapper<WrongQuestion> wrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WrongQuestion::getQuestionId,questionDTO.getId());
            WrongQuestion wrongQuestion = wrongQuestionMapper.selectOne(wrapper);
            if (wrongQuestion == null){
                throw new DataErrorException(MessageConstant.NULL_DATA);
            }
            queryWrapper.eq(Question::getId,questionDTO.getId());
            Question question = quetsionsMapper.selectOne(queryWrapper);
            if (question.getQuestionType()== QuestionType.SINGLE_CHOICE){
                if (normalizeAnswer(question.getAnswer()).equals(normalizeAnswer(questionDTO.getAnswer()))){
                    CorrectQuestionNum+=1;
                    totalScores+=VXConstant.SINGLE_CHOICE_SCORE;
                    wrongQuestionMapper.delete(wrapper);
                }else {
                    WrongQuestionNum+=1;
                }
            }
            if (question.getQuestionType()== QuestionType.MULTIPLE_CHOICE){
                if (normalizeAnswer(question.getAnswer()).equals(normalizeAnswer(questionDTO.getAnswer()))){
                    CorrectQuestionNum+=1;
                    totalScores+=VXConstant.MULTIPLE_CHOICE_SCORE;
                    wrongQuestionMapper.delete(wrapper);
                }else {
                    WrongQuestionNum+=1;
                }
            }
        }
        WrongQuestionScoreVO wrongQuestionScoreVO = new WrongQuestionScoreVO();
        wrongQuestionScoreVO.setWrongQuestionNum(WrongQuestionNum);
        wrongQuestionScoreVO.setTotalScores(totalScores);
        wrongQuestionScoreVO.setCorrectQuestionNum(CorrectQuestionNum);
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            throw new DataErrorException("用户未登录或登录已过期");
        }
        com.ddm.entity.vxEntity.User user = userMapper.selectById(currentUserId);
        if (user == null) {
            throw new DataErrorException("用户信息不存在");
        }
        wrongQuestionScoreVO.setUserName(user.getUserName());
        return wrongQuestionScoreVO;
    }

    private String normalizeAnswer(String answer) {
        if (answer == null || answer.trim().isEmpty()) {
            return "";
        }
        // 处理无逗号的答案（如 "ACD" → "A,C,D"）
        String normalized = answer.replaceAll("([A-Za-z])", "$1,")  // 字母后加逗号
                .replaceAll(",+,", ",")          // 去重逗号
                .replaceAll("^,|,$", "");        // 去除首尾逗号
        return Arrays.stream(normalized.split(","))
                .map(String::trim)
                .map(String::toUpperCase)
                .sorted()
                .collect(Collectors.joining(","));
    }
}
